package com.ch.forum.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class FileUtils {


    /**
     * 上传到指定路径
     * @param file
     * @param filePath
     * @param fileName
     * @throws Exception
     */
    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }


    /**
     * 读取文件，并输出
     * eg：
     *      1.读取本地图片，直接展示在页面上
     * @param filePath
     * @param response
     * @throws Exception eg：IOException、NullException
     */
    public static void readFileAndOutput(String filePath, HttpServletResponse response) throws Exception {
        FileInputStream fis = new FileInputStream(filePath);
        int i = fis.available();
        byte[] buff = new byte[i];
        fis.read(buff);
        fis.close();
        response.setHeader("Content-type","image/jpg");
        OutputStream out = response.getOutputStream();
        out.write(buff);
        out.close();
    }
}
